<template>
  <div class="main">
    <h2>系统消息</h2>
    <div class="card-box">
      <a-form layout="inline" class="clearfix" :form="form" @submit="handleSubmit">
        <a-form-item label="关键字：">
          <a-input placeholder="请输入系统消息标题" v-decorator="['keyword']" />
        </a-form-item>
        <a-form-item label="状态：">
          <a-select style="width: 120px" v-decorator="['status', { initialValue: '' }]" placeholder="全部">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option v-for="item in readStatus" :value="item.value" :key="item.key">{{ item.label
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="消息分类：">
          <a-select style="width: 150px" v-decorator="['type', { initialValue: '' }]" placeholder="全部">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option v-for="item in sysMsgTypes" :value="item.dictValue" :key="item.dictValue">{{ item.dictLabel
              }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="推送时间">
          <a-range-picker :placeholder="['开始日期', '结束日期']" v-decorator="['Date']">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <a-button class="f-right mt-5" type="primary" html-type="submit">搜索</a-button>
        <a-button class="f-right mr-10 mt-5" style="color:#909399;" @click="clear">重置</a-button>
      </a-form>
    </div>
    <div>
      <div style="margin-bottom: 16px">
        <a-button type="primary" class="mr-10" :disabled="!hasSelected" :loading="loading"
          @click="batchUpdate">设置为已读</a-button>
        <a-button type="danger" @click="batchDelete">批量删除</a-button>
        <span style="margin-left: 8px">
          <template v-if="hasSelected"></template>
        </span>
      </div>
      <a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :columns="columns"
        :data-source="data" :pagination="ipagination" :rowKey="record => record.id">
        <span slot="type" slot-scope="text,record">
          {{ sysMsgTypes.find(item => item.dictValue == text).dictLabel }}
        </span>

        <span slot="action" slot-scope="text,record">
          <a @click="seeEdit(record)" style="margin-right:32px;text-align:right">查看详情</a>
          <a @click="delEdit(record)" style="text-align:right !important">删除</a>
        </span>
      </a-table>
    </div>
    <!-- 1:根据需求推荐产品;2:系统消息;3:下架提醒  5 根据产品推荐需求 -->
    <!-- 模态框 -->
    <a-modal v-model="NeedVisible" title="产品推荐" :width="800" :closable="false" :maskClosable="false">
      <ul class="messageCompany">
        <li><span>需求名称：</span><span style="color: #188AF1;font-weight:bold;font-size: 18px;cursor:pointer"
            @click="toDetail(currentObj.demand.id)">{{ currentObj.demand ? currentObj.demand.demandProductName : '/'
            }}</span>
        </li>
        <li><span>需求编号：</span>{{ currentObj.demand ? currentObj.demand.demandNo : '/' }}</li>
        <li><span>产品类别：</span>{{ currentObj.demand ? currentObj.demand.productOneCategoryName : '/' }}-{{
          currentObj.demand
            ?
            currentObj.demand.productSecondCategoryName : '' }}</li>
        <!-- <li><span>价格(元)：</span>{{ currentObj.demand? currentObj.demand.price:'面谈'}}</li> -->
        <li><span>价格(元)：</span>{{ NeedPrice }}</li>
        <li>
          <span>我们为您推荐：</span>
          <div v-for="(item, index) in currentObj.products" :key="index">
            <a href="#" @click="toProductDetail(item.id)" style="color: #188AF1;font-weight:bold;font-size:18px">{{
              item.productName }}</a>
            <!-- <span @click="toProductDetail(item.id)" style="color: #188AF1;cursor:pointer;font-size:16px">{{ item.productName }}</span> -->
          </div>
        </li>
      </ul>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="close">关闭</a-button>
      </template>
    </a-modal>

    <a-modal v-model="ProductVisible" title="需求推荐" :width="800" :closable="false" :maskClosable="false">
      <ul class="messageCompany">
        <li>
          <span>产品名称：</span>
          <span style="color: #188AF1;font-weight:bold;font-size: 18px;cursor:pointer"
            @click="toProductDetail(currentObj.product.id)">{{ currentObj.product ? currentObj.product.productName : '/'
            }}
          </span>
          <!-- <a href="#" @click="toProductDetail(currentObj.product.id)" style="color: #188AF1;font-weight:bold;font-size: 18px;" >
            {{currentObj.product?currentObj.product.productName:'/'}}
          </a> -->
        </li>
        <li><span>产品编号：</span>{{ currentObj.product ? currentObj.product.productNo : '/' }}</li>
        <!-- <li><span>价格(元)：</span>{{ currentObj.product?currentObj.product.price:'面谈' }}</li>
        <li><span>供应上限：{{ currentObj.product?currentObj.product.productCeiling:'不限'}}</span></li> -->
        <li><span>预算价格(元)：</span>{{ productPrice }}</li>
        <li><span>供应上限：<span>{{ productCeiling }}</span></span></li>
        <li>
          <span>我们为您推荐：</span>
          <div v-for="(item, index) in currentObj.demands" :key="index">
            <a href="#" @click="toDetail(item.id)" style="color: #188AF1;cursor:pointer;font-size:16px">{{
              item.demandProductName }}</a>
          </div>
        </li>
      </ul>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="close"> 关闭 </a-button>
      </template>
    </a-modal>

    <a-modal v-model="SystemVisible" title="系统消息" :width="800" :closable="false" :maskClosable="false">
      <ul class="messageCompany">
        <li><span>标题：</span><span style="color: #188AF1;font-weight:bold;font-size: 18px;">{{ currentObj.title }}</span>
        </li>
        <li v-if="ShowPass"><span>未通过理由：</span><span style="color: #188AF1;font-size:16px">{{ currentObj.messageContent
            }}</span></li>
        <li v-else>
          <div v-if="currentObj.messageContent != ''">
            内容：<span style="color: #188AF1;font-size:16px">{{ currentObj.messageContent }}</span>
          </div>
        </li>
      </ul>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="close"> 关闭 </a-button>
      </template>
    </a-modal>

    <a-modal v-model="DownVisible" title="下架提醒" :width="800" :closable="false" :maskClosable="false">
      <ul class="messageCompany">
        <li><span>标题：</span><span style="color: #188AF1;font-weight:bold;font-size: 18px;">{{ currentObj.title }}</span>
        </li>
        <li><span>下架提醒：</span><span style="color: #188AF1;font-size:16px">{{ currentObj.messageContent }}</span></li>
      </ul>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="close"> 关闭 </a-button>
      </template>
    </a-modal>

    <!-- <a-modal v-model="DownVisible" title="下架提醒" :width="800" :closable="false" :maskClosable="false">
      <ul class="messageCompany">
        <li><span>标题：</span>{{ currentObj.title }}</li>
        <li>
          <span>未通过理由：</span>{{ currentObj.messageContent }}
        </li>
        <li>
          <span>下架提醒：</span>您发布的编号为{{  }}产品：{{  }}（名称）即将在14天后自动下架，请及时续期。
        </li>
      </ul>
      <template slot="footer">
        <a-button key="submit" type="primary" @click="close"> 关闭 </a-button>
      </template>
    </a-modal> -->
  </div>
</template>

<script>
import moment from "moment";
import {
  getListSystemMessage,
  getSystemObjMessage,
  deleteSystemMessage,
  updateSystemMessage,
} from "@/apis/user/System";

import { listSysMsg, msgIsRead, msgBathRead, delSysMsg, bathDelSysMsg } from '@/apis/system/msg'

import { GetSearchinfo } from "@/apis/user/MaterialsDemand";
import { getInfo } from "@/apis/productProvide";
import { getDicts } from "@/apis/system";
import { getCookiesUserInfo } from "@/utils/auth"; // get token from cookie

const columns = [
  {
    title: "序号",
    dataIndex: "id",
    customRender: (text, record, index) => `${index + 1}`, // 显示每一行的序
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "消息分类",
    dataIndex: "type",
    scopedSlots: { customRender: "type" },
    // customRender: function (text) {
    //   if (text) {
    //     const obj = this.sysMsgTypes.find(item => item.dictValue == text)
    //     if (obj) {
    //       return obj.dictLabel
    //     }
    //     return ''

    //   }
    // },
  },
  {
    title: "推送时间",
    dataIndex: "createTime",
  },
  {
    title: "消息状态",
    dataIndex: "status",
    customRender: function (text) {
      if (text == 0) {
        return "未读";
      } else if (text == 1) {
        return "已读";
      }
    },
  },
  {
    title: "操作",
    dataIndex: "action",
    scopedSlots: { customRender: "action" },
  },
];

const data = [];

export default {
  data () {
    return {
      sysMsgTypes: [],
      NeedPrice: "",
      productPrice: "",
      productCeiling: "",
      ShowPass: false,
      NeedVisible: false,
      SystemVisible: false,
      ProductVisible: false,
      DownVisible: false,
      contentForm: {},
      currentObj: {}, //点击查看=>当前的对象
      alreadyRead: "", //设为已读ID
      deleteIds: "", //删除的Id
      unReadIds: "", //未读的Id
      readStatus: [
        {
          label: "未读",
          key: "1",
          value: 0,
        },
        {
          label: "已读",
          key: "2",
          value: 1,
        },
      ],
      messageType: [
        {
          label: "产品推荐",
          key: "1",
          value: 1,
        },
        {
          label: "系统消息",
          key: "2",
          value: 2,
        },
        {
          label: "下架提醒",
          key: "3",
          value: 3,
        },
        {
          label: "需求推荐",
          key: "5",
          value: 5,
        },
        {
          label: "企业变更",
          key: "8",
          value: 8
        },
        {
          label: "产品变更",
          key: "9",
          value: 9
        },
        {
          label: "需求变更",
          key: "10",
          value: 10
        },
        {
          label: "解决方案变更",
          key: "11",
          value: 11
        }
      ],
      ipagination: {
        current: 1,
        total: 0,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "30", "40", "50"],
        showTotal: (total) => `共有 ${total} 条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) =>
          this.onSizeChange(current, pageSize),
        onChange: (page, pageSize) => this.onPageChange(page, pageSize),
      },
      data,
      columns,
      selectedRowKeys: [],
      loading: false,
      lineForm: {},
      form: this.$form.createForm(this, { name: "coordinated" }),

    };
  },
  created () {
    this.toGetListSystemMessage();
    this.getSysMsgTypes()
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0;
    },
  },
  methods: {
    /** 获取消息分类字典 */
    async getSysMsgTypes () {
      const { data } = await getDicts("sys_msg_type");
      console.log('获取消息分类字典', data);

      this.sysMsgTypes = data
    },
    toDetail (id) {
      let routeData = this.$router.resolve({
        path: "/MaterialDetails",
        query: { id },
      });
      window.open(routeData.href, "_blank");
    },
    toProductDetail (id) {
      let routeData = this.$router.resolve({
        path: "/ProductContent",
        query: { id },
      });
      window.open(routeData.href, "_blank");
    },
    //获取系统消息分页列表
    toGetListSystemMessage () {
      console.log('this.lineForm', this.lineForm);

      let params = {
        pageSize: this.ipagination.pageSize,
        PageNum: this.ipagination.current,
        ...this.lineForm,
        userId: JSON.parse(getCookiesUserInfo()).userId,
      };
      listSysMsg(params).then((res) => {
        console.log('res', res);

        if (res.code == 200) {

          this.data = res.rows;
          this.ipagination.total = res.total;
          this.$store.dispatch("getNoReadMsgCount");
        }
      });
    },
    // 分页搜索
    onPageChange (page, pageSize) {
      this.ipagination.current = page;
      this.toGetListSystemMessage();
    },
    // 页容量改变
    onSizeChange (current, pageSize) {
      this.ipagination.pageSize = pageSize;
      this.ipagination.current = current;
      this.toGetListSystemMessage();
    },
    // 搜索
    handleSubmit (e) {
      e.preventDefault();
      this.ipagination.current = 1;
      this.form.validateFields((err, values) => {
        if (!err) {
          if (values.Date != undefined && values.Date.length > 0) {
            values.sendDateStart = moment(values.Date[0]).format("YYYY-MM-DD");
            values.sendDateEnd = moment(values.Date[1]).format("YYYY-MM-DD");
          }
          this.lineForm = {
            title: values.keyword,
            status: values.status
              ? Number(values.status)
              : values.status,
            type: values.type
              ? Number(values.type)
              : values.type,
            createTimeStart: values.sendDateStart,
            createTimeEnd: values.sendDateEnd,
          };
        }
        this.toGetListSystemMessage();
      });
    },
    // 清空表单
    clear () {
      this.form.resetFields()
      this.lineForm = {}
      this.onPageChange(1)
    },
    // 选择操作
    onSelectChange (value, selectedRowKeys) {
      this.selectedRowKeys = value
      let unRead = []
      unRead = selectedRowKeys.filter((item) => item.readStatus == 0); //留下状态0=>未读的
      if (unRead.length > 0) {
        this.unReadIds = unRead.map((item, index) => item.id).join(","); //未读的
      }
    },
    // 批量修改系统消息为已读或单个修改
    batchUpdate () {
      console.log('this.selectedRowKeys', this.selectedRowKeys);
      msgBathRead(this.selectedRowKeys).then((res) => {
        if (res.code == 200) {
          this.selectedRowKeys = [];
          this.$message.success("设置成功");
          this.$store.dispatch("getNoReadMsgCount");
          this.loading = false;
          this.toGetListSystemMessage()
        }
      });

      // if (this.unReadIds == "") {
      //   this.loading = false;
      //   this.$message.warning("请选择留言状态未读的选项");
      //   this.selectedRowKeys = [];
      // }
      // let params = {
      //   id: this.unReadIds,
      // };
      // console.log('this.unReadIds', this.unReadIds);

      return
      updateSystemMessage(params).then((res) => {
        if (res.code == 200) {
          this.selectedRowKeys = [];
          this.$message.success("设置成功");
          this.loading = false;
          this.toGetListSystemMessage();
        }
      });
    },
    // 批量删除或单个删除系统消息
    batchDelete () {
      const that = this
      // this.deleteIds = this.selectedRowKeys.join(',')
      this.deleteIds = [...this.selectedRowKeys];
      if (this.deleteIds == '') {
        this.$message.warning("请选择要删除的选项")
        this.selectedRowKeys = []
      } else {
        this.$confirm({
          title: "您确定要删除此信息吗?",
          okText: "确定",
          okType: "danger",
          cancelText: "取消",
          onOk () {
            // 点击确定
            that.sureBatchDelete().then

          },
          onCancel () { }
        })
      }
    },
    // 确定删除
    sureBatchDelete () {
      // let params = {
      //   id: this.deleteIds,
      // };
      bathDelSysMsg(this.deleteIds).then((res) => {
        if (res.code == 200) {
          this.selectedRowKeys = [];
          this.$message.success("删除成功");
          if (this.data.length == 1) {
            // 如果只有最后一条就刷新上一页
            this.ipagination.current--;
          }
          if (this.ipagination.current < 1) {
            this.ipagination.current = 1;
          }

          this.toGetListSystemMessage();
        }
      });
    },
    // 删除
    delEdit (item) {
      var that = this;
      this.$confirm({
        title: "您确定要删除此信息吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk () {
          // 点击确定
          // let params = { id: item.id };
          delSysMsg(item.id).then((res) => {
            if (res.code == 200) {
              that.$message.success("删除成功");
              if (that.data.length == 1) {
                // 如果只有最后一条就刷新上一页
                that.ipagination.current--;
              }
              if (that.ipagination.current < 1) {
                that.ipagination.current = 1;
              }
              that.toGetListSystemMessage();
            }
          });
        },
        onCancel () {
          // 点击取消
          console.log("Cancel");
        },
      });
    },
    async seeEdit (item) {
      const { id } = JSON.parse(item.content)
      if (item.status == 0) {
        // 变更为已读
        await msgIsRead(item.id)
        this.$store.dispatch("getNoReadMsgCount");
      }
      // 工单类审核消息
      if (["13", "14", "15", "16"].includes(item.type)) {
        this.$router.push({
          path: '/usercenter/CreditFinancialDetail',
          query: {
            id: id,
            companyId: item.companyId,
            flg: 'detail'
          }
        })
      }
      // 企业变更审核结果
      if (item.type == '00') {
        this.$router.push({
          path: '/usercenter/BaseInformation',
          // query: {
          //   id: id,
          //   companyId: item.companyId,
          //   flg: 'detail'
          // }
        })
      }
      // 资质证明审核结果
      if (["01", "02"].includes(item.type)) {
        this.$router.push({
          path: '/usercenter/NewQualification',
          query: {
            id,
            companyId: item.companyId,
            look: true
          }
        })
      }
      return



      this.alreadyRead = item.id;
      // 1:根据需求推荐产品
      // 2:系统消息
      // 3:下架提醒
      // 5:根据产品推荐需求
      let params = { id: item.id };
      getSystemObjMessage(params).then((res) => {
        if (res.code == 200) {
          if (item.messageType == 1) {
            // 1:根据需求推荐产品
            // this.currentObj = JSON.parse(res.data.messageContent)
            let obj = JSON.parse(res.data.messageContent);
            if (obj.demand.price == null) {
              this.NeedPrice = "面谈";
            } else {
              this.NeedPrice = obj.demand.price;
            }
            this.currentObj = obj;
            console.log(666, this.currentObj);
            this.NeedVisible = true;
          } else if (item.messageType == 2) {
            let str = res.data.title;
            let num = str.indexOf("未通过");
            if (Number(num) > 0) {
              this.ShowPass = true;
            } else {
              this.ShowPass = false;
            }
            this.currentObj = res.data;
            this.SystemVisible = true;
          } else if (item.messageType == 3 || item.messageType == 7) {
            // 3:下架提醒
            this.currentObj = res.data;
            this.DownVisible = true;
          } else if (item.messageType == 5) {
            // 5:根据产品推荐需求
            // productPrice: '',
            // productCeiling:'',
            let obj = JSON.parse(res.data.messageContent);
            if (obj.product.price == null) {
              this.productPrice = "面谈";
            } else {
              this.productPrice = obj.product.price;
            }
            if (obj.product.productCeiling == "") {
              this.productCeiling = "不限";
            } else {
              this.productCeiling = obj.product.productCeiling;
            }
            this.currentObj = obj;
            // this.currentObj = JSON.parse(res.data.messageContent)
            console.log(777, this.currentObj);
            this.ProductVisible = true;
          } else if (item.messageType == 9) {    // 产品
            let { data } = res
            let anchor = ''
            if (data.title.includes('基本信息')) {
              anchor = 'baseInfo'
            } else if (data.title.includes('产品详情')) {
              anchor = 'detailInfo'
            } else if (data.title.includes('联系方式')) {
              anchor = 'lineInfo'
            }
            this.close()
            let routerData = this.$router.resolve({
              path: '/ProductContent',
              query: {
                id: data.objectId,
                anchor
              }
            })
            window.open(routerData.href, '_blank')
          } else if (item.messageType == 8) {    // 企业
            let { data } = res
            let anchor = ''
            if (data.messageContent == 1) {
              anchor = 'baseInfo'
            } else if (data.messageContent == 2) {
              anchor = 'QCInfo'
            } else if (data.messageContent == 3) {
              anchor = 'HAInfo'
            }
            this.close()
            let routerData = this.$router.resolve({
              path: '/entdetails',
              query: {
                id: data.objectId,
                anchor
              }
            })
            window.open(routerData.href, '_blank')
          } else if (item.messageType == 10) {   // 需求
            let { data } = res
            this.close()
            let routerData = this.$router.resolve({
              path: '/MaterialDetails',
              query: {
                id: data.objectId,
                anchor: 'materDetail'
              }
            })
            window.open(routerData.href, '_blank')
          } else if (item.messageType == 11) {   // 解决方案
            let { data } = res
            let anchor = ''
            if (data.messageContent == 4 || data.messageContent == 8) {
              anchor = 'baseConInfo'
            } else if (data.messageContent == 5) {
              anchor = 'serviceInfo'
            } else if (data.messageContent == 6) {
              anchor = 'serviceGuRY'
            } else if (data.messageContent == 7) {
              anchor = 'ryInfo'
            }
            this.close()
            let routerData = this.$router.resolve({
              path: '/ProgrammeContent',
              query: {
                id: data.objectId,
                anchor
              }
            })
            window.open(routerData.href, '_blank')
          }
        }
      });
    },
    // 查看详情关闭=>设为已读
    close () {
      // console.log(99, this.currentObj);
      let params = { id: this.alreadyRead };
      updateSystemMessage(params).then((res) => {
        if (res.code == 200) {
          this.toGetListSystemMessage();
        }
      });
      this.currentObj = {};
      (this.NeedVisible = false),
        (this.ProductVisible = false),
        (this.DownVisible = false),
        (this.SystemVisible = false);
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  padding: 16px 24px;
  background-color: #ffffff;
  border-radius: 4px;

  span {
    a {
      color: #188af1;
    }
  }

  h2 {
    font-size: 22px;
    color: #303133;
    margin-bottom: 24px;
  }

  .card-box {
    padding: 16px;
    margin-bottom: 24px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.messageCompany {
  padding: 20px;
  border-radius: 4px;
  background: #f5f7fa;
  overflow: hidden;

  li {
    line-height: 24px;
    width: 100%;
    float: left;

    span {
      font-weight: bold;
    }

    a {
      color: #188af1;
    }

    &:first-child {
      width: 100%;
      color: #303133;
      border-bottom: 1px dashed #dcdfe6;
      margin-bottom: 10px;
      height: auto;
      padding-bottom: 10px;
    }
  }
}
</style>